<?php

namespace App\Console\Commands\Cruise;

use App\Enums\WorkOrder\OrderEnum;
use App\Models\Common\ResourcesModel;
use App\Models\OpenShop\Common\ShopArchiveModel;
use App\Models\Recognize\RecognizeBusinessLicenseResult;
use App\Models\Recognize\RecognizeFoodProduceLicenseResult;
use App\Models\WorkOrder\WorkOrderApplyMainModel;
use Illuminate\Console\Command;

class AddCruiseShopArchive extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'cruise:add_cruise_shop_archive';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '初始化门店档案-营业执照和食品许可证';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $time      = time();
        $batchData = [];
        WorkOrderApplyMainModel::query()
            ->with('resourcesRel')
            ->where('status', OrderEnum::MAIN_STATUS_FINISH)
            ->where('problemPid', OrderEnum::PROBLEM_PID_5)
            ->whereIn('problemChildId', [OrderEnum::PROBLEM_PID_5_CHILDREN_100, OrderEnum::PROBLEM_PID_5_CHILDREN_101, OrderEnum::PROBLEM_PID_5_CHILDREN_102])
            ->chunk(100, function ($item) use (&$batchData) {
                foreach ($item as $v) {
                    if (count($v->resourcesRel) > 0) {
                        foreach ($v->resourcesRel as $resources) {
                            if ($resources->name == 'businessLicenseImg') {//营业执照
                                $info = RecognizeBusinessLicenseResult::query()
                                    ->where('url', $resources->url)
                                    ->first();//查询营业执照识别结果表
                                if ($info && $info['business']) {
                                    $batchData[$v->shopId]['businessLicenseImg'] = [
                                        'businessLicense'          => $info['business'],                               //营业执照 - 经营范围
                                        'businessLicenseStartDate' => $info['establishDate'] ?? "",                    //营业执照 - 发证日期
                                        'businessLicenseEndDate'   => $info['validPeriod'] ?? '',                      //营业执照 - 到期日期（永久：9999-12-13）
                                        'businessLicenseUrl'       => $resources->url,                                 //营业执照 - url
                                    ];
                                }
                            }
                            if ($resources->name == 'foodBusinessLicenseImg') {//食品经营许可证
                                $info = RecognizeFoodProduceLicenseResult::query()
                                    ->where('url', $resources->url)
                                    ->first();//查询食品经营许可证识别结果表
                                if ($info && $info['foodType']) {
                                    $batchData[$v->shopId]['foodBusinessLicenseImg'] = [
                                        'foodBusinessLicense'          => $info['foodType'],                             //食品经营许可证 - 经营范围
                                        'foodBusinessLicenseStartDate' => $info['issueDate'] ?? "",                      //食品经营许可证 - 发证日期
                                        'foodBusinessLicenseEndDate'   => $info['validToDate'] ?? '',                    //食品经营许可证 - 到期日期（永久：9999-12-13）
                                        'foodBusinessLicenseUrl'       => $resources->url,                               //食品经营许可证 - url
                                    ];
                                }
                            }
                        }
                    }
                }
            });

        if ($batchData) {

            //删除所有数据
            ShopArchiveModel::query()->truncate();

            foreach (array_chunk($batchData, 500, true) as $chunk) {//批量新增
                $insertData = [];
                foreach ($chunk as $k => $v) {
                    if ($v) {
                        $vData = [
                            'shopId'                       => $k,
                            'createdAt'                    => $time,
                            'businessLicense'              => '',                                    //营业执照 - 经营范围
                            'businessLicenseStartDate'     => '',                                    //营业执照 - 发证日期
                            'businessLicenseEndDate'       => '',                                    //营业执照 - 到期日期（永久：9999-12-13）
                            'foodBusinessLicense'          => '',                                    //食品经营许可证 - 经营范围
                            'foodBusinessLicenseStartDate' => '',                                    //食品经营许可证 - 发证日期
                            'foodBusinessLicenseEndDate'   => '',                                    //食品经营许可证 - 到期日期（永久：9999-12-13）
                        ];
                        if (isset($v['businessLicenseImg'])) {
                            $vData['businessLicense']          = (string)$v['businessLicenseImg']['businessLicense'];
                            $vData['businessLicenseStartDate'] = (string)$v['businessLicenseImg']['businessLicenseStartDate'];
                            $vData['businessLicenseEndDate']   = (string)$v['businessLicenseImg']['businessLicenseEndDate'];
                        }
                        if (isset($v['foodBusinessLicenseImg'])) {
                            $vData['foodBusinessLicense']          = (string)$v['foodBusinessLicenseImg']['foodBusinessLicense'];
                            $vData['foodBusinessLicenseStartDate'] = (string)$v['foodBusinessLicenseImg']['foodBusinessLicenseStartDate'];
                            $vData['foodBusinessLicenseEndDate']   = (string)$v['foodBusinessLicenseImg']['foodBusinessLicenseEndDate'];
                        }
                        $insertData[] = $vData;
                    }
                }
                if ($insertData) {
                    ShopArchiveModel::query()->insert($insertData);
                }
            }
            //新增之后-资源url更新
            ShopArchiveModel::query()
                ->chunk(100, function ($item) use ($batchData) {
                    foreach ($item as $v) {
                        $resources = [];
                        if (isset($batchData[$v['shopId']])) {
                            if ($v['businessLicense']) {
                                $resources['businessLicenseImg'] = $batchData[$v['shopId']]['businessLicenseImg']['businessLicenseUrl'];
                            }
                            if ($v['foodBusinessLicense']) {
                                $resources['foodBusinessLicenseImg'] = $batchData[$v['shopId']]['foodBusinessLicenseImg']['foodBusinessLicenseUrl'];
                            }
                            if ($resources) {
                                //保存资源
                                ResourcesModel::moduleBusinessResourcesUpdate(
                                    $resources,
                                    ResourcesModel::MODULE_TYPE_SHOP,
                                    ResourcesModel::BUSINESS_SHOP_ARCHIVE,
                                    (int)$v['id'],
                                );
                            }
                        }
                    }
                });
        }
    }
}
